const http = require('http')
const fs = require('fs')

http.createServer((request, response) => {
  const { url, method } = request
  if(url === '/' && method === 'GET'){
    fs.readFile('index.html', (err, data) => {
      if(err){
        response.setHeader('content-type', 'text/plain;charset=utf-8')
        response.statusCode = 500
        response.end('500 服务端错误~')
        return
      }   
      response.setHeader('content-type', 'text/html;charset=utf-8')
      response.end(data)
    })
  }
  
  else if(url === '/users' && method === 'GET'){
    response.setHeader('content-type', 'application/json')
    response.end(JSON.stringify({name: "csh", age: 20}))
  }

  else{
    response.statusCode = 404
    response.setHeader('content-type', 'text/plain;charset=utf-8')
    response.end('404 not found')
  }
  
}).listen(3000, () => {
  console.log('Server start on 3000')
})